<template>
  <div class="container">
    <n-page-header title="我的钱包" @back="router.back" />

    <div class="dashboard">
      <n-grid cols="6" x-gap="12" y-gap="12" responsive="screen" item-responsive>
        <n-gi span="6 m:3 l:2">
          <n-card title="我的金币" :bordered="false" embedded>
            <n-spin :size="16" v-if="requesting"></n-spin>
            <n-text v-else>{{ walletData?.coin ?? '加载失败' }}</n-text>
          </n-card>
        </n-gi>
        <n-gi span="6 m:3 l:4" style="display: flex; align-items: end">
          <div style="display: flex; flex-direction: column">
            <n-space vertical>
              <n-p depth="3" style="margin: 0">
                本网站的虚拟货币，可用于付费咨询
              </n-p>
              <n-p depth="3" style="margin: 0">
                1元人民币对应1金币，提现收取5%手续费
              </n-p>
            </n-space>
            <n-space style="margin-top: .5rem">
              <n-button type="primary" @click="recharge">金币充值</n-button>
              <n-button @click="settle">金币提现</n-button>
            </n-space>
          </div>
          <n-modal v-model:show="modal.show" transform-origin="center">
            <n-card
                style="width: 300px"
                :title="modal.title"
                :bordered="false"
                role="dialog"
                aria-modal="true"
            >
              <n-input-number
                  :min="modal.input.min"
                  :max="modal.input.max"
                  :validator="modal.input.validator"
                  :show-button="false"
                  v-model:value="modal.input.value"
                  :placeholder="modal.input.placeholder"
                  @keydown.enter="modal.positive"
              >
                <template #suffix>
                  金币
                </template>
              </n-input-number>

              <template #footer>
                <n-space  style="display: flex; align-items: center; justify-content: end">
                  <n-button type="primary"
                            @click="modal.positive"
                            :loading="modal.requesting"
                            :disabled="modal.requesting"
                  >
                    确定
                  </n-button>
                  <n-button @click="modal.negative">取消</n-button>
                </n-space>
              </template>
            </n-card>
          </n-modal>
        </n-gi>
      </n-grid>
    </div>
    <div class="settle-list">
      <n-h3 prefix="bar">提现记录</n-h3>
      <n-list>
        <n-list-item v-for="item in settleList" :key="item.id" :ref="setSettleItemRef">
          <n-thing>
            <template #header>
              <n-p depth="3">提现编号：{{item.id}}</n-p>
            </template>

            <template #description>
              <n-space>
                <n-text>提现金币：{{item.coin}}</n-text>
                <n-text>实际到账：{{item.money}}元</n-text>
              </n-space>
            </template>

            <template #footer>
              <n-p depth="3">{{item.date}}</n-p>
            </template>
          </n-thing>
        </n-list-item>
      </n-list>
      <div class="list-status">
        <div class="list-loading" v-if="settleFetching">
          <n-spin :size="18" />
        </div>
        <div class="list-no-more" v-if="settleListNoMore">
          <n-p depth="3">没有更多了</n-p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {useRouter} from "vue-router";
import {h, ref, nextTick} from "vue";
import {useRequests} from "@/common/requests.js";
import {useMessage, useNotification} from "naive-ui";
import {useIntersectionObserver} from "@vueuse/core";

const router = useRouter()
const requests = useRequests()
const message = useMessage()
const notify = useNotification()

const modal = ref({
  show: false,
  title: null,
  content: null,
  input: {
    min: 1,
    max: 1000,
    placeholder: null,
    value: null,
    validator: null
  },
  requesting: false,
  positive: () => {},
  negative: () => {
    modal.value.show = false
  }
})

const walletData = ref({})
const requesting = ref(false)
const fetchWallet = () => {
  requesting.value = true
  requests.wallet.getMe().then(resp => {
    requesting.value = false
    if (resp.ret === 0) {
      walletData.value = resp.data
    } else {
      message.error(resp?.data ?? resp?.msg ?? "未知错误")
    }
  }).catch(err => {
    requesting.value

    notify.error({content: "出错了", meta: err.toString(), duration: 1500})
  })
}

const settleList = ref([])
const settleItemRef = ref([])
const setSettleItemRef = el => {
  settleItemRef.value.push(el)
}

const settleListNoMore = ref(false)
const settlePage = ref({
  page: 0,
  offset: 20
})

const settleFetching = ref(false)
const fetchSettle = refresh => {
  if (settleFetching.value) {
    return false
  }

  settleFetching.value = true
  if (refresh) {
    settleItemRef.value = []
    settleListNoMore.value = false
    settlePage.value.page = 0
  }

  settlePage.value.page ++
  requests.wallet.settleLog(settlePage.value).then(resp => {
    settleFetching.value = false
    if (resp.ret === 0) {
      if (refresh) {
        settleList.value = resp.data
      } else {
        settleList.value.push(...resp.data)
      }

      if (resp.data.length < settlePage.value.offset) {
        settleListNoMore.value = true
      } else {
        nextTick(() => {
          const item = settleItemRef.value[settleItemRef.value.length - 2]
          const { stop } = useIntersectionObserver(item, ([{ isIntersecting }]) => {
            if (isIntersecting) {
              stop()
              fetchSettle()
            }
          })
        })
      }
    } else {
      message.error(resp?.data ?? resp?.msg ?? "未知错误")
    }
  }).catch(err => {
    settleFetching.value = false

    console.log(err)
    notify.error({content: "出错了", meta: err.toString(), duration: 1500})
  })
}

const recharge = () => {
  modal.value = {...modal.value, ...{
      show: true,
      title: '金币充值',
      input: {
        min: 1,
        max: 10000,
        placeholder: "最低充值1金币",
        validator: x => Number.isInteger(x)
      },
      positive() {
        modal.value.requesting = true
        requests.wallet.recharge({coin: modal.value.input.value}).then(resp => {
          modal.value.requesting = false
          if (resp.ret === 0) {
            modal.value.show = false
            fetchWallet()

            message.success("充值成功")
          } else {
            message.error(resp?.data ?? resp?.msg ?? "未知错误")
          }
        }).catch(err => {
          modal.value.requesting = false

          console.log(err)
          notify.error({content: "出错了", meta: err.toString(), duration: 1500})
        })
      }
    }
  }
}

const settle = () => {
  modal.value = {...modal.value, ...{
      show: true,
      title: '金币提现',
      input: {
        min: 10,
        max: walletData.value?.coin ?? 10000,
        placeholder: "最低10金币提现",
        validator: x => Number.isInteger(x)
      },
      positive() {
        modal.value.requesting = true
        requests.wallet.settle({coin: modal.value.input.value}).then(resp => {
          modal.value.requesting = false
          if (resp.ret === 0) {
            modal.value.show = false
            fetchWallet()
            fetchSettle(true)

            message.success("提现成功")
          } else {
            message.error(resp?.data ?? resp?.msg ?? "未知错误")
          }
        }).catch(err => {
          modal.value.requesting = false

          console.log(err)
          notify.error({content: "出错了", meta: err.toString(), duration: 1500})
        })
      }
    }
  }
}

fetchWallet()
fetchSettle()
</script>

<style lang="scss" scoped>
.container {
  .dashboard {
    margin-top: 1rem;
  }

  .settle-list {
    margin-top: 1.5rem;

    .list-status {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>
